// 打开数据库
const request = indexedDB.open('myDatabase', 1);

request.onupgradeneeded = (event) => {
  const db = event.target.result;
  if (!db.objectStoreNames.contains('myObjectStore')) {
    const objectStore = db.createObjectStore('myObjectStore', { keyPath: 'id' });
    objectStore.createIndex('nameIndex', 'name', { unique: false });
  }
};

request.onsuccess = (event) => {
  const db = event.target.result;

  // 插入数据
  const newData = { id: 1, name: 'Alice', age: 25 };
  const addTransaction = db.transaction('myObjectStore', 'readwrite');
  const addObjectStore = addTransaction.objectStore('myObjectStore');
  const addRequest = addObjectStore.add(newData);

  addRequest.onsuccess = (event) => {
    console.log('数据插入成功');

    // 查询数据
    const getTransaction = db.transaction('myObjectStore', 'readonly');
    const getObjectStore = getTransaction.objectStore('myObjectStore');
    const getRequest = getObjectStore.get(1);

    getRequest.onsuccess = (event) => {
      const result = event.target.result;
      if (result) {
        console.log('查询结果:', result);

        // 更新数据
        const updatedData = { id: 1, name: 'Alice Smith', age: 26 };
        const updateTransaction = db.transaction('myObjectStore', 'readwrite');
        const updateObjectStore = updateTransaction.objectStore('myObjectStore');
        const updateRequest = updateObjectStore.put(updatedData);

        updateRequest.onsuccess = (event) => {
          console.log('数据更新成功');

          // 删除数据
          const deleteTransaction = db.transaction('myObjectStore', 'readwrite');
          const deleteObjectStore = deleteTransaction.objectStore('myObjectStore');
          const deleteRequest = deleteObjectStore.delete(1);

          deleteRequest.onsuccess = (event) => {
            console.log('数据删除成功');
          };

          deleteRequest.onerror = (event) => {
            console.error('数据删除失败', event.target.error);
          };
        };

        updateRequest.onerror = (event) => {
          console.error('数据更新失败', event.target.error);
        };
      } else {
        console.log('未找到对应数据');
      }
    };

    getRequest.onerror = (event) => {
      console.error('数据查询失败', event.target.error);
    };
  };

  addRequest.onerror = (event) => {
    console.error('数据插入失败', event.target.error);
  };
};

request.onerror = (event) => {
  console.error('数据库打开失败', event.target.error);
};